/*
 *  atBudget Personal Finance Management application
 *
 *  Copyright 2011, Ilia Frenkel <frenkel.ilia@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
	Transactions controller handles all interactions with transactions.
 */

Ext.define('ATB.controller.Transactions', {
    extend: 'Ext.app.Controller',
	views: [
		'transaction.List',
		'transaction.Create'
	],
	stores: [
		'Transactions',
		'Categories',
		'Payees',
		'Accounts'
	],
	models: [
		'Transaction'
	],
	refs: [{
		ref: 'list',
		selector: 'transactionlist'
	}],
	/*
		Setup event handlers.
	*/
    init: function() {
		this.control({
			'transactionlist button[action=addtransaction]': {
				click: this.openNewTransaction
			},
			'transactionlist button[action=newtransaction]': {
				click: this.createTransaction
			},
			'transactionlist' : {
				selectionchange: this.setButtonsState
			},
			'transactionlist button[action=showhidequickentry]' : {
				toggle: this.showHideQuickEntry
			},
			'transactioncreate button[action=save]': {
				click: this.createTransaction
			},
			'transactioncreate button[action=newcategory]': {
				click: function() {this.getController('Main').manageCategories();}
			},
			'transactioncreate button[action=newpayee]': {
				click: function() {this.getController('Payees').openNewPayee();}
			},
			'transactioncreate button[action=newaccount]': {
				click: function() {this.getController('Accounts').openNewAccount();}
			}
		});//this.control

		this.application.on({
			accountchanged: this.onAccountChanged,
			scope: this
		});//accountchanged
    },//init

	/*
		Open new transaction dialogue. Nothing exciting here - just create
		the view.
	*/
	openNewTransaction: function (button) {
		var view = Ext.widget('transactioncreate');
	},//openNewTransaction
	
	/*
		An event handler for "Save" button in the create transaction dialogue.
		Collects the values from the form, create new record, adds it to
		the store and calls	sync on the store which triggers communication
		with the server. Any error during the communication is handled by 
		the model's proxy.
	*/
	createTransaction: function(btn) {
		//get the form - it can be "Quick Entry" form or the one from
		//"New Transaction" dialogue
		var form = btn.up('window') ? btn.up('window').down('form') : btn.up('form');

		//if we failed to get a form we have a problem - do nothing because
		//there are no values for new transaction
		if (!form) {
			Ext.Msg.show({
				title: 'Error',
				msg: 'Unfortunately and unexpected error has occurred. If you '+
					'plan to report this error to the developers please '+
					'mention the following: "Form was not found while '+
					'creating transaction".',
				buttons: Ext.Msg.OK,
				width: 400,
				icon: 'atb-icon-error'
			});
			return;
		}

		//check if all the fields in the form are valid and highlight the
		//invalid ones
		if (!form.form.isValid()) {
			Ext.Msg.show({
				title: 'Error',
				msg: 'You have to fill some fields before pressing the button.'+
				' Please check the fields highlighted in red.',
				buttons: Ext.Msg.OK,
				width: 400,
				icon: 'atb-icon-exclamation'
			});
			return;
		}
		
		//gather initial information from the form
		var values = form.getValues();
		
		//check whether isDebit button exists and if yes whether it is pressed
		var isDebitBtn = form.down('button[name=isdebit]')
		var isDebit    = isDebitBtn ? isDebitBtn.pressed : false;
		
		//get the stores
		var txStore  = this.getTransactionsStore();
		var catStore = this.getCategoriesStore();
		var accStore = this.getAccountsStore();
		var payStore = this.getPayeesStore();
		
		var selectedAcc = txStore.selectedAccount;

		//add timestamp to the values
		values.timestamp = Ext.util.Format.date(new Date(), 'U');
		
		//figure out whether it is debit, credit or transfer and set
		//toaccount and fromaccount correspondingly
		if (isDebitBtn.pressed) {//debit
			values.fromaccount = selectedAcc.data;
			if (values.account) {//transfer FROM selected account
				values.toaccount = accStore.getById(values.account).data;
			}
		} else {//credit
			values.toaccount = selectedAcc.data;
			if (values.account) {//transfer TO selected account
				values.fromaccount = accStore.getById(values.account).data;
			}
		}
		
		//set category and its parent if any
		if (values.category) {
			values.category = catStore.getNodeById(values.category).data;
			if (values.category.parentid != 0) {
				values.category.parent = 
					catStore.getNodeById(values.category.parentid).data;
			}
		}
		
		//set payee
		if (values.payee) {
			values.payee = payStore.getById(values.payee).data;
		}
		
		//create new transaction record
		//var record = txStore.create(values);
		var record = this.getTransactionModel().create(values);

		//add record to the store and sync with the server
		txStore.add(record);
		txStore.sync();

		//clear the form
		form.form.reset();
		
		//if we used "New Transaction" dialogue close it
		if (btn.up('window')) btn.up('window').close();
	},//createTransaction

	/*
		Event handler for transaction list. Disables/enables "Edit" and "Remove"
		buttons according to selection.
	*/
	setButtonsState: function(view, sel, opts) {
		var view = this.getList(),
			edtBtn = view.down('button[action=edittransaction]'),
			delBtn = view.down('button[action=deletetransaction]');
		if (sel.length > 0) {
			edtBtn.enable();
			delBtn.enable();
		} else {
			edtBtn.disable();
			delBtn.disable();
		}
	},//setButtonsState
	
	/*
		Event handler that fires when an account is selected from the list.
		This event is fired from changeSelectedAccount method of the Main 
		controller.
	*/
	onAccountChanged: function(recs) {
		var view = this.getList();
		var addBtn = view.down('button[action=addtransaction]');
		var newBtn = view.down('button[action=newtransaction]');
		if (recs.length > 0) {//enable buttons
			addBtn.enable();
			newBtn.enable();
			//update account balance
			var accBalanceTxt = view.down('toolbar[name=tablefooter]').down('tbtext[name=accountbalance]');
			if (recs[0].data.balance > 0) {
				accBalanceTxt.setText('<span style="color:#339933">'+recs[0].data.balancefmt+'</span>');
			} else {
				accBalanceTxt.setText('<span style="color:#993333">'+recs[0].data.balancefmt+'</span>');
			}
		} else {//disable buttons
			addBtn.disable();
			newBtn.disable();
		}
	},//onAccountChanged

	/*
		Show or hide Quick Entry toolbar.
	*/
	showHideQuickEntry: function(button, pressed, opts) {
		var view = this.getList();
		var tb = view.getDockedItems('[name=quickentryform]')[0];
		if (tb) {
			if (pressed) {
				tb.show();
			} else {
				tb.hide();
			}
		}
	},//showHideQuickEntry

	/*
		Refresh payees store when manage payees dialogue is shown to
		fetch any changes from the server before we make new ones.
	*/
	refreshStore: function() {
		this.getPayeesStore().load();
	}//refreshStore
});